package user03.handler;

import cn.hutool.json.JSONUtil;
import common05.common.Results;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class SecurityAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        log.error("您没有权限访问地址！url=[{}] ip=[{}] username=[{}]  exception=[{}]", request.getRequestURI(), request.getRemoteAddr(), username, e.getMessage());
        PrintWriter writer = response.getWriter();
        writer.write(JSONUtil.toJsonStr(Results.forbidden()));
        writer.flush();
        writer.close();
    }

}
